<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

// 加载数据
$groups = json_decode(file_get_contents('groups.json'), true) ?? [];
$users = json_decode(file_get_contents('users.json'), true) ?? [];
$roomId = $_GET['room_id'] ?? null;

$group = null;
foreach ($groups as &$g) {
    if ($g['id'] == $roomId) {
        $group = &$g;
        break;
    }
}

if (!$group) {
    die("群聊不存在或已解散。");
}

// 验证用户是否为管理员
if ($group['admin'] !== $_SESSION['username']) {
    die("您无权限管理此群聊。");
}

// 踢出用户逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'kick') {
    $username = $_POST['username'];
    if ($group['admin'] === $_SESSION['username']) {
        $group['members'] = array_filter($group['members'], fn($m) => $m !== $username);
        file_put_contents('groups.json', json_encode($groups));
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>群成员管理</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>成员管理</h1>
    <ul>
        <?php foreach ($group['members'] as $member): ?>
            <?php
            $memberEmail = '';
            foreach ($users as $user) {
                if ($user['username'] === $member) {
                    $memberEmail = $user['email'];
                    break;
                }
            }
            ?>
            <li>
                <?= htmlspecialchars($member) ?> (<?= htmlspecialchars($memberEmail) ?>)
                <?php if ($group['admin'] === $_SESSION['username'] && $member !== $_SESSION['username']): ?>
                    <form method="POST" onsubmit="return confirm('确认踢出 <?= htmlspecialchars($member) ?> 吗？');" style="display: inline;">
                        <input type="hidden" name="action" value="kick">
                        <input type="hidden" name="username" value="<?= htmlspecialchars($member) ?>">
                        <button type="submit">踢出</button>
                    </form>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
</body>
</html>